#coding=utf-8
'''
Created on 2009-11-15

@author: Administrator
'''
import re,email
import codecs
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from mod.member import Member
from mod.tag import Tag
from mod.blog import Blog
from mod.recmail import RecMail
class MailBlog(InboundMailHandler):
    '''
    classdocs
    '''
    def goodDecode(self,encodedPayload): 
        encoding = encodedPayload.encoding 
        payload = encodedPayload.payload 
        if encoding and encoding.lower() != '7bit': 
            payload = payload.decode(encoding) 
            return payload 


    def receive(self,message):
        '''
        Constructor
        '''
        
            
        
        
        h = email.Header.Header(message.subject.decode("gb2312"))
        dh = email.Header.decode_header(h)
        if dh[0][1]:
            subj = dh[0][0].decode(dh[0][1])
        else:
            subj = dh[0][0]
        
        bodies = message.bodies(content_type='text/plain')
        allBodies = ""; 
        

        for body in bodies:
            
            # body[0] = "text/plain"
            # body[1] = EncodedPayload --> body[1].decode()
            text = body[1].decode().decode("gb2312")
            allBodies = allBodies + "\n" + text

        recmail = RecMail(sender=message.sender,subject=subj,content=allBodies)
        recmail.put()
        
        #emails = re.findall(r'[0-9a-zA-Z_]{1,}@[0-9a-zA-Z_-]{1,}?.[0-9a-zA-Z_-]{2,}.[a-zA-Z]{0,}.[a-zA-Z]{2,3}', message.sender)
        emails = email.utils.parseaddr(message.sender)
        member = Member().getMemberByEmail(emails[1])
        
        tag = Tag().getTag("beta")
        
        #bodies = message.bodies(content_type='text/plain')
        #content = subject
        #for body in bodies:
        #    content = content + "\n---------------------------\n" + body[1].decode()
        if member:    
            blog = Blog(author=member,tag=tag,content=recmail.subject)
            blog.put()
            
    